#!/usr/bin/env bash
set -euo pipefail
# Usage: ./run_injection.sh <runs> <mode> <strategy>
# mode: vulnerable | defense
# strategy: random | fixed_offset | every (inject every run)

runs=${1:-200}
mode=${2:-vulnerable}
strategy=${3:-random}

echo "Running $runs runs mode=$mode strategy=$strategy"
mkdir -p logs
gcc -O2 bench/matmul.c -o bench/matmul

unset FI_INJECT FI_OFFSET FI_BIT FI_MODE
./bench/matmul > golden.txt
golden=$(cat golden.txt)

echo "run,injected,offset,bit,rc,outcome,output,mode,strategy" > logs/results.csv

max_bytes=$((64*64*8))

for ((i=1;i<=runs;i++)); do
  injected=0; offset=NA; bit=NA; rc=0
  export FI_MODE=$mode

  case "$strategy" in
    random)
      if (( i % 2 == 0 )); then injected=1; fi
      ;;
    fixed_offset)
      if (( i % 2 == 0 )); then injected=1; offset=1234; bit=$(( (i+3) % 8 )); fi
      ;;
    every)
      injected=1
      ;;
    *)
      if (( i % 2 == 0 )); then injected=1; fi
      ;;
  esac

  if [ "$injected" -eq 1 ]; then
    if [ "$offset" = "NA" ]; then offset=$(( RANDOM % max_bytes )); fi
    if [ "$bit" = "NA" ]; then bit=$(( RANDOM % 8 )); fi
    export FI_INJECT=1
    export FI_OFFSET=$offset
    export FI_BIT=$bit
  else
    unset FI_INJECT FI_OFFSET FI_BIT || true
  fi

  out=$(./bench/matmul 2>&1) || rc=$?
  if [ -z "${rc+x}" ]; then rc=0; fi

  outcome="OK"
  if [ "$rc" -ne 0 ]; then
    if echo "$out" | grep -q DETECTED_MISMATCH; then outcome="DETECTED"; else outcome="CRASH"; fi
  else
    if [ "$out" != "$golden" ]; then outcome="SDC"; fi
  fi

  echo "$i,$injected,$offset,$bit,$rc,$outcome,$out,$mode,$strategy" >> logs/results.csv
  echo "run $i injected=$injected outcome=$outcome"
done

echo "Completed. Results: logs/results.csv"
